package com.itheima.balance;

import java.util.ArrayList;

public class Hash {
    ArrayList<String> ips;
    
    public Hash(String nodeNames) {
        System.out.println("init list : " + nodeNames);
        String[] nodes = nodeNames.split(",");
        //初始化服务器列表，长度取机器数
        ips = new ArrayList<>(nodes.length);
        for (String node : nodes) {
            ips.add(node);
        }
    }
    
    //添加节点，注意，添加节点会造成内部Hash重排，思考为什么呢？？？
    //这是个问题！在一致性hash中会进入详细探讨
    void addnode(String nodeName) {
        System.out.println("add node : " + nodeName);
        ips.add(nodeName);
    }
    
    //移除
    void remove(String nodeName) {
        System.out.println("remove node : " + nodeName);
        ips.remove(nodeName);
    }
    
    //映射到key的算法，这里取余数做下标
    private int hash(String ip) {
        int last = Integer.valueOf(ip.substring(ip.lastIndexOf(".") + 1, ip.length()));
        return last % ips.size();
    }
    
    //请求
    //注意，这里和来访ip是有关系的，采用一个参数，表示当前的来访ip
    void request(String ip) {
        //下标
        int i = hash(ip);
        System.out.println(ip + "-->" + ips.get(i));
    }
    
    public static void main(String[] args) {
        Hash hash = new Hash("192.168.0.1,192.168.0.2");
        for (int i = 1; i < 10; i++) {
            //模拟请求的来源ip
            String ip = "192.168.0." + i;
            hash.request(ip);
        }
        
        hash.addnode("192.168.0.3");
        for (int i = 1; i < 10; i++) {
            //模拟请求的来源ip
            String ip = "192.168.0." + i;
            hash.request(ip);
        }
        
        hash.remove("192.168.0.2");
        for (int i = 1; i < 10; i++) {
            //模拟请求的来源ip
            String ip = "192.168.0." + i;
            hash.request(ip);
        }
    }
    
}
